<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2021/9/6
 * Time: 13:59
 */
namespace app\admin\controller;

use app\index\service\ExtendService;
use app\middleware\AdminCheck;
use OSS\OssClient;
use think\facade\Db;
use think\facade\Log;

class Question {

    protected $middleware = [
        AdminCheck::class => ['except' 	=> ['latestQuestion'] ]
    ];


    /**
     * 添加题目获取添加最新一道题的题号和章节
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function latestQuestion(){
        validateParam('city_','city_');
        $city_ = input('city_');
        //获取最新一个题目的信息
        $question = Db::name('question')
            ->where('city_',$city_)
            ->order('no_ desc')
            ->find();
        if(empty($question)){
            $data['chapter_'] = 1;
            $data['no_'] = 1;
            return success('最新题目信息',$data);
        }
        $data['chapter_'] = $question['chapter_'];
        $data['no_'] = $question['no_'] + 1;
        return success('最新题目信息',$data);
    }



    /**
     *   @SWG\Post(
     *     path="/admin/question/add",
     *     tags={"后台考试相关"},
     *     summary="添加试题",
     *     consumes={"application/json"},
     *     produces={"application/json"},
     *     @SWG\Parameter(
     *      in="query",
     *      required=true,
     *      name="no_,type_,chapter_,question_,an1_,an2_,an3_,an4_,an5_,an6_,an7_,an8_,an9_,an10_,answer_true,city_,explain_",
     *      type="string",
     *      description="no_（第几题）,type_(题目类型：1为判断题，2为单选题，3为多选题),chapter_(章节的 id),question_（题目名称）,an1_,an2_,an3_,an4_,an5_,an6_,an7_,an8_,an9_,an10_,answer_true（第几个是正确选项（数字））,explain_（答案解析）"),
     *     @SWG\Response(response="200",description="ok")
     *  )
     */
    /**
     * 添加题目
     * @return \think\response\Json
     * @throws \OSS\Core\OssException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add(){
        validateParam('no_,type_,chapter_,question_,an1_,an2_,answer_true,city_','no_,type_,chapter_,question_,an1_,an2_,answer_true,city_');
        $param = input();
        $data['no_']=input('no_');//第几题
        $data['type_'] = input('type_');
        $data['chapter_'] = input('chapter_');//章节的id
        $data['question_'] = input('question_');//题目名称
        $data['question_image'] = input('question_image');//题目的图片
        $data['an1_'] = input('an1_');
        $data['an2_'] = input('an2_');
        $data['an3_'] = input('an3_');
        $data['an4_'] = input('an4_');
        $data['an5_'] = input('an5_');
        $data['an6_'] = input('an6_');
        $data['an7_'] = input('an7_');
        $data['an8_'] = input('an8_');
        $data['an9_'] = input('an9_');
        $data['an10_'] = input('an10_');
        $data['answer_true'] = input('answer_true');
        $data['city_'] = input('city_');//关联的城市
        $data['explain_'] = input('explain_');//试题的解析

        $temp = [
            '1'=>'A',
            '2'=>'B',
            '3'=>'C',
            '4'=>'D',
            '5'=>'E',
            '6'=>'F',
            '7'=>'G',
            '8'=>'H',
            '9'=>'I',
            '10'=>'J',
        ];
        $service = new ExtendService();
        $token = cache('voiceToken');
        if(empty($token)){
            $token_object = $service->getalyuntoken(config('system.ali')['accessKeyId'],config('system.ali')['accessKeySecret']);
            Log::info('这里是获取token打印：'.json_encode($token_object));
            $token = $token_object['Token']['Id'];
            cache('voiceToken',$token,1*60);
        }
        //获取语音文件
        if($param['type_'] == '1'){
            $question_type = '判断题';
            if($param['answer_true'] == '1'){
                $answer = '正确';
            }else{
                $answer = '错误';
            }
            $text = "{$question_type}，{$param['question_']}。答案是：{$answer}";
        }elseif ($param['type_'] == '2'){
            $question_type = '单选题';
            $answer = $temp[$param['answer_true']];
            $xuanxiang = '';
            if(!empty($param['an1_'])){
                $xuanxiang = $xuanxiang.'A '.$param['an1_'].'。';
            }
            if(!empty($param['an2_'])){
                $xuanxiang = $xuanxiang.'B '.$param['an2_'].'。';
            }
            if(!empty($param['an3_'])){
                $xuanxiang = $xuanxiang.'C '.$param['an3_'].'。';
            }
            if(!empty($param['an4_'])){
                $xuanxiang = $xuanxiang.'D '.$param['an4_'].'。';
            }
            if(!empty($param['an5_'])){
                $xuanxiang = $xuanxiang.'E '.$param['an5_'].'。';
            }
            if(!empty($param['an6_'])){
                $xuanxiang = $xuanxiang.'F '.$param['an6_'].'。';
            }
            if(!empty($param['an7_'])){
                $xuanxiang = $xuanxiang.'G '.$param['an7_'].'。';
            }
            if(!empty($param['an8_'])){
                $xuanxiang = $xuanxiang.'H '.$param['an8_'].'。';
            }
            if(!empty($param['an9_'])){
                $xuanxiang = $xuanxiang.'I '.$param['an9_'].'。';
            }
            if(!empty($param['an10_'])){
                $xuanxiang = $xuanxiang.'J '.$param['an10_'].'。';
            }
            $text = "{$question_type}，{$param['question_']}。{$xuanxiang}答案是：{$answer}。";
        }else{
            $answer = '';
            $question_type = '多选题';
            $aa = explode(' ',$param['answer_true']);
            foreach ($aa as $kk=>$vv){
                $answer = $answer . $temp[$vv];
            }
            $xuanxiang = '';
            if(!empty($param['an1_'])){
                $xuanxiang = $xuanxiang.'A '.$param['an1_'].'。';
            }
            if(!empty($param['an2_'])){
                $xuanxiang = $xuanxiang.'B '.$param['an2_'].'。';
            }
            if(!empty($param['an3_'])){
                $xuanxiang = $xuanxiang.'C '.$param['an3_'].'。';
            }
            if(!empty($param['an4_'])){
                $xuanxiang = $xuanxiang.'D '.$param['an4_'].'。';
            }
            if(!empty($param['an5_'])){
                $xuanxiang = $xuanxiang.'E '.$param['an5_'].'。';
            }
            if(!empty($param['an6_'])){
                $xuanxiang = $xuanxiang.'F '.$param['an6_'].'。';
            }
            if(!empty($param['an7_'])){
                $xuanxiang = $xuanxiang.'G '.$param['an7_'].'。';
            }
            if(!empty($param['an8_'])){
                $xuanxiang = $xuanxiang.'H '.$param['an8_'].'。';
            }
            if(!empty($param['an9_'])){
                $xuanxiang = $xuanxiang.'I '.$param['an9_'].'。';
            }
            if(!empty($param['an10_'])){
                $xuanxiang = $xuanxiang.'J '.$param['an10_'].'。';
            }
            $text = "{$question_type}，{$param['question_']}。{$xuanxiang}答案是：{$answer}。";
        }
        $text = urlencode($text);
        $appkey=config('system.ali')['aliVoiceKey'];
        $url="https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/tts?appkey={$appkey}&token={$token}&text={$text}&format=mp3&voice=aijia";
        $stream_data = http_get($url);
        $url = app()->getRootPath().'/public/voice/'.createNo().'.mp3';
        file_put_contents($url, $stream_data, true); // 保存文件
        $ossClient = new OssClient(config('system.ali')['accessKeyId'], config('system.ali')['accessKeySecret'], config('system.ali')['endpoint']);
        $bucket = config('system.ali')['bucket'];
        $object = 'voice/'.createNo().'.mp3';
        $filePath = $url;
        $result = $ossClient->uploadFile($bucket, $object, $filePath);
        $voice_file = $result['info']['url'];
        $voice_file = str_replace('http','https',$voice_file);
        $data['voice_file'] = $voice_file;//语音文件
        Db::name('question')->insert($data);
        return success('添加成功');
    }


    /**
     * 章节列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getChapterList(){
        validateParam('city_','city_');
        $param=input();
        $where[]=['city_','=',$param['city_']];

        $list=Db::name('chapter')
            ->where($where)
            ->select();
        return success('章节列表',['list'=>$list]);
    }




    /**
     *   @SWG\Post(
     *     path="/admin/question/getList",
     *     tags={"后台考试相关"},
     *     summary="试题列表",
     *     consumes={"application/json"},
     *     produces={"application/json"},
     *     @SWG\Parameter(
     *      in="query",
     *      required=true,
     *      name="pageNo,pageSize",
     *      type="string",
     *      description="pageNo(第几页),pageSize（一页多少条数据）,city_（城市）,chapter_(章节的id)，type_(试题类型（题目类型：1为判断题，2为单选题，3为多选题），question_（题目名称）)"),
     *     @SWG\Response(response="200",description="ok")
     *  )
     */
    /**
     * 试题列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList(){
        validateParam('city_,chapter_,pageNo,pageSize','city_,pageNo,pageSize');
        $param=input();
        $where[]=['city_','=',$param['city_']];
        if(!empty($param['chapter_'])){
            $where[]=['chapter_','=',$param['chapter_']];
        }
        //题目类型筛选
        if(!empty($param['type_'])){
            $where[]=['type_','=',$param['type_']];
        }
        //题目名称筛选
        if(!empty($param['question_'])){
            $where[]=['question_','like',"%{$param['question_']}%"];
        }
        //获取总数
        $total=Db::name('question')
            ->where($where)
            ->count();
        $offset=makeOffset($param['pageNo'],$param['pageSize']);

        $list=Db::name('question')
            ->where($where)
            ->limit($offset,$param['pageSize'])
            ->select();
        return success('题目列表',['total'=>$total,'list'=>$list]);
    }



    /**
     *   @SWG\Post(
     *     path="/admin/question/edit",
     *     tags={"后台考试相关"},
     *     summary="编辑题目",
     *     consumes={"application/json"},
     *     produces={"application/json"},
     *     @SWG\Parameter(
     *      in="query",
     *      required=true,
     *      name="id_,no_,type_,chapter_,question_,an1_,an2_,an3_,an4_,an5_,an6_,an7_,an8_,an9_,an10_,answer_true,city_,explain_",
     *      type="string",
     *      description="id_,no_(第几题),type_(题目类型：1为判断题，2为单选题，3为多选题),chapter_(章节的 id),question_（题目名称）,an1_,an2_,an3_,an4_,an5_,an6_,an7_,an8_,an9_,an10_,answer_true（第几个是正确选项（数字））,explain_（答案解析）"),
     *     @SWG\Response(response="200",description="ok")
     *  )
     */
    /**
     * 编辑题目
     * @return \think\response\Json
     * @throws \OSS\Core\OssException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit(){
        validateParam('no_,type_,chapter_,question_,an1_,an2_,answer_true,city_','no_,type_,chapter_,question_,an1_,an2_,answer_true,city_');
        $param = input();
        $data['no_']=input('no_');//第几题
        $data['type_'] = input('type_');
        $data['chapter_'] = input('chapter_');//章节的id
        $data['question_'] = input('question_');//题目名称
        $data['question_image'] = input('question_image');//题目的图片
        $data['an1_'] = input('an1_');
        $data['an2_'] = input('an2_');
        $data['an3_'] = input('an3_');
        $data['an4_'] = input('an4_');
        $data['an5_'] = input('an5_');
        $data['an6_'] = input('an6_');
        $data['an7_'] = input('an7_');
        $data['an8_'] = input('an8_');
        $data['an9_'] = input('an9_');
        $data['an10_'] = input('an10_');
        $data['answer_true'] = input('answer_true');
        $data['city_'] = input('city_');//关联的城市
        $data['explain_'] = input('explain_');//试题的解析

        $temp = [
            '1'=>'A',
            '2'=>'B',
            '3'=>'C',
            '4'=>'D',
            '5'=>'E',
            '6'=>'F',
            '7'=>'G',
            '8'=>'H',
            '9'=>'I',
            '10'=>'J',
        ];
        $service = new ExtendService();
        $token = cache('voiceToken');
        if(empty($token)){
            $token_object = $service->getalyuntoken(config('system.ali')['accessKeyId'],config('system.ali')['accessKeySecret']);
            $token = $token_object['Token']['Id'];
            cache('voiceToken',$token,1*60);
        }
        //获取语音文件
        if($param['type_'] == '1'){
            $question_type = '判断题';
            if($param['answer_true'] == '1'){
                $answer = '正确';
            }else{
                $answer = '错误';
            }
            $text = "{$question_type}，{$param['question_']}。答案是：{$answer}";
        }elseif ($param['type_'] == '2'){
            $question_type = '单选题';
            $answer = $temp[$param['answer_true']];
            $xuanxiang = '';
            if(!empty($param['an1_'])){
                $xuanxiang = $xuanxiang.'A '.$param['an1_'].'。';
            }
            if(!empty($param['an2_'])){
                $xuanxiang = $xuanxiang.'B '.$param['an2_'].'。';
            }
            if(!empty($param['an3_'])){
                $xuanxiang = $xuanxiang.'C '.$param['an3_'].'。';
            }
            if(!empty($param['an4_'])){
                $xuanxiang = $xuanxiang.'D '.$param['an4_'].'。';
            }
            if(!empty($param['an5_'])){
                $xuanxiang = $xuanxiang.'E '.$param['an5_'].'。';
            }
            if(!empty($param['an6_'])){
                $xuanxiang = $xuanxiang.'F '.$param['an6_'].'。';
            }
            if(!empty($param['an7_'])){
                $xuanxiang = $xuanxiang.'G '.$param['an7_'].'。';
            }
            if(!empty($param['an8_'])){
                $xuanxiang = $xuanxiang.'H '.$param['an8_'].'。';
            }
            if(!empty($param['an9_'])){
                $xuanxiang = $xuanxiang.'I '.$param['an9_'].'。';
            }
            if(!empty($param['an10_'])){
                $xuanxiang = $xuanxiang.'J '.$param['an10_'].'。';
            }
            $text = "{$question_type}，{$param['question_']}。{$xuanxiang}答案是：{$answer}。";
        }else{
            $answer = '';
            $question_type = '多选题';
            $aa = explode(' ',$param['answer_true']);
            foreach ($aa as $kk=>$vv){
                $answer = $answer . $temp[$vv];
            }
            $xuanxiang = '';
            if(!empty($param['an1_'])){
                $xuanxiang = $xuanxiang.'A '.$param['an1_'].'。';
            }
            if(!empty($param['an2_'])){
                $xuanxiang = $xuanxiang.'B '.$param['an2_'].'。';
            }
            if(!empty($param['an3_'])){
                $xuanxiang = $xuanxiang.'C '.$param['an3_'].'。';
            }
            if(!empty($param['an4_'])){
                $xuanxiang = $xuanxiang.'D '.$param['an4_'].'。';
            }
            if(!empty($param['an5_'])){
                $xuanxiang = $xuanxiang.'E '.$param['an5_'].'。';
            }
            if(!empty($param['an6_'])){
                $xuanxiang = $xuanxiang.'F '.$param['an6_'].'。';
            }
            if(!empty($param['an7_'])){
                $xuanxiang = $xuanxiang.'G '.$param['an7_'].'。';
            }
            if(!empty($param['an8_'])){
                $xuanxiang = $xuanxiang.'H '.$param['an8_'].'。';
            }
            if(!empty($param['an9_'])){
                $xuanxiang = $xuanxiang.'I '.$param['an9_'].'。';
            }
            if(!empty($param['an10_'])){
                $xuanxiang = $xuanxiang.'J '.$param['an10_'].'。';
            }
            $text = "{$question_type}，{$param['question_']}。{$xuanxiang}答案是：{$answer}。";
        }
        $text = urlencode($text);
        $appkey=config('system.ali')['aliVoiceKey'];
        $url="https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/tts?appkey={$appkey}&token={$token}&text={$text}&format=mp3&voice=aijia";
        $stream_data = http_get($url);
        $url = app()->getRootPath().'/public/voice/'.createNo().'.mp3';
        file_put_contents($url, $stream_data, true); // 保存文件
        $ossClient = new OssClient(config('system.ali')['accessKeyId'], config('system.ali')['accessKeySecret'], config('system.ali')['endpoint']);
        $bucket = config('system.ali')['bucket'];
        $object = 'voice/'.createNo().'.mp3';
        $filePath = $url;
        $result = $ossClient->uploadFile($bucket, $object, $filePath);
        $voice_file = $result['info']['url'];
        $voice_file = str_replace('http','https',$voice_file);
        $data['voice_file'] = $voice_file;//语音文件
        Db::name('question')
            ->where('id_',input('id_'))
            ->update($data);
        return success('编辑成功');
    }




    /**
     *   @SWG\Post(
     *     path="/admin/question/delete",
     *     tags={"后台考试相关"},
     *     summary="删除题目",
     *     consumes={"application/json"},
     *     produces={"application/json"},
     *     @SWG\Parameter(
     *      in="query",
     *      required=false,
     *      name="ids",
     *      type="string",
     *      description="ids"),
     *     @SWG\Response(response="200",description="ok")
     *  )
     */
    /**
     * 删除题目
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function delete(){
        validateParam('ids','ids');
        //首先判断章节是否存在题库
        Db::name('question')
            ->where('id_','in',input('ids'))
            ->delete();
        return success('删除成功');
    }



}